﻿/*
 * Author: XYZ.SEAN.M.THX 
 * Email: seanmpthx@gmail.com
 * Copyright: (c) 2010-2020
 * Version:0.1
 * 
 * <Update>
 *   创建于 2012-06-01
 * </Update>
 * <Remark>
 * 使用Win32 API 对INI文件进行操作
 * </Remark>
*/

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace XYZShell.CsHelper.ConfigHelper
{
    /// <summary>
    /// INI文件的简单操作类
    /// </summary>
   public class INIHelper
    {
       private string IniPath;
       [DllImport("kernel32")]
       private static extern long WritePrivateProfileString(string section,string key,string val,string filepath);
       [DllImport("kernel32")]
       private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retval,int size,string filepath);
       public INIHelper(string filepath)
       {
           this.IniPath = filepath;
       }
       /// <summary>
       /// 创建INI文件，如果文件存在，不再创建
       /// </summary>
       public void Create()
       {
           if (!this.ExistINIFile())
           {
               File.Create(IniPath);
           }
       }
       /// <summary>
       /// 删除INI文件
       /// </summary>
       public void Delete()
       {
           if (this.ExistINIFile())
           {
               File.Delete(IniPath);
           }
       }
       /// <summary>
       /// 设置INI文件KEY值
       /// </summary>
       /// <param name="section">段落</param>
       /// <param name="key">KEY</param>
       /// <param name="value">VALUE</param>
       public void SetValue(string section,string key,string value)
       {
           WritePrivateProfileString(section, key, value, this.IniPath);
       }
       /// <summary>
       /// 获取INI文件KEY值
       /// </summary>
       /// <param name="section">段落</param>
       /// <param name="key">KEY</param>
       /// <returns>VALUE</returns>
       public string GetValue(string section,string key)
       {
           StringBuilder sb = new StringBuilder(500);
           int i = GetPrivateProfileString(section,key,"",sb,500,this.IniPath);
           return sb.ToString();
       }
       /// <summary>
       /// INI文件是否存在
       /// </summary>
       /// <returns>存在返回TRUE</returns>
       public bool ExistINIFile()
       {
           return File.Exists(IniPath);
       }
    }
}
